package cn.ahaoweb.drule.core;

import cn.ahaoweb.drule.core.constant.DruleStringConstants;
import cn.ahaoweb.drule.core.configuration.RuleServiceConfiguration;
import cn.ahaoweb.drule.core.util.ExecuteLogger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @Name: DebugRuleSessionImpl
 * @Description: 主要用于输出调试信息
 * @Author: wangzhonghao
 * @Date: 2025/2/14 11:02
 */
public class DebugRuleSessionImpl extends RuleSessionImpl {

    private static final Logger log = LoggerFactory.getLogger(DebugRuleSessionImpl.class);

    public static final String ENTER = "ENTER";
    public static final String PRE_HANDLED = "PRE_HANDLED";
    public static final String EXECUTED = "EXECUTED";
    public static final String POST_HANDLED = "POST_HANDLED";
    public static final String EXIT = "EXIT";

    private static final ThreadLocal<ExecuteLogger> executeLoggerThreadLocal = new ThreadLocal<>();

    private boolean debug = false;

    public DebugRuleSessionImpl(RuleService ruleService) {
        super(ruleService);
        if (ruleService.getConfig().exist(RuleServiceConfiguration.EXECUTE_MODE.DEBUG)) {
            this.debug = true;
        }
    }

    @Override
    protected void enter(FactInfo factInfo) {
        ExecuteLogger logger = new ExecuteLogger();
        logger.setChild(new ExecuteLogger());
        factInfo.attach(DruleStringConstants.LOGGER, logger);
        logger.add("入参", String.valueOf(factInfo.getInput()));
        if (debug) {
            logger.getChild().add(ENTER, null, false);
        }
        executeLoggerThreadLocal.set(logger);
    }

    @Override
    protected void afterPreHandlers(FactInfo factInfo) {
        if (debug) {
            ExecuteLogger logger = executeLoggerThreadLocal.get();
            logger.getChild().add(PRE_HANDLED, null, false);
        }
    }

    @Override
    protected void afterExecuted(FactInfo factInfo) {
        if (debug) {
            ExecuteLogger logger = executeLoggerThreadLocal.get();
            logger.getChild().add(EXECUTED, null, false);
        }
    }

    @Override
    protected void afterPostHandlers(FactInfo factInfo) {
        if (debug) {
            ExecuteLogger logger = executeLoggerThreadLocal.get();
            logger.getChild().add(POST_HANDLED, null, false);
        }
    }

    @Override
    protected void exit(FactInfo factInfo) {
        ExecuteLogger logger = executeLoggerThreadLocal.get();
        logger.add("出参", String.valueOf(factInfo.getOutput()));
        logger.add("命中规则", String.valueOf(factInfo.getFiredRules()));
        if (debug) {
            logger.getChild().add(EXIT, null, false);
            logger.add("耗时明细",logger.getChild().timesConsumeDetail());
        }
        // 防止内存泄漏
        executeLoggerThreadLocal.remove();
        log.info("RuleService[{}] 执行记录:\n{}", ruleService.signature(), logger.getContent());
    }

}
